package com.haotunet.app.goldtreasure.activity;

import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.haotunet.app.goldtreasure.R;
import com.haotunet.app.goldtreasure.db.DBOpenHelper;
import com.haotunet.app.goldtreasure.model.BankInfo;
import com.haotunet.app.goldtreasure.model.BaseModel;
import com.haotunet.app.goldtreasure.model.CardBean;
import com.haotunet.app.goldtreasure.model.CardInfo;
import com.haotunet.app.goldtreasure.model.OrderInfo;
import com.haotunet.app.goldtreasure.model.PeopleBean;
import com.haotunet.app.goldtreasure.net.ActionUtil;
import com.haotunet.app.goldtreasure.net.ParserUtil;
import com.haotunet.app.goldtreasure.other.Interface.OnPassBackListener;
import com.haotunet.app.goldtreasure.utils.ActivityUtils;
import com.haotunet.app.goldtreasure.utils.Strs;
import com.haotunet.app.goldtreasure.utils.UIHelper;
import com.haotunet.app.goldtreasure.utils.XEditUtils;
import com.haotunet.app.goldtreasure.views.DialogWidget;
import com.haotunet.app.goldtreasure.views.MyAlertDialog;
import com.haotunet.app.goldtreasure.views.PayPasswordView;
import com.haotunet.app.goldtreasure.views.PayPasswordView.OnPayListener;
import com.haotunet.app.goldtreasure.views.TipPopupView;
import com.haotunet.app.goldtreasure.views.TitleView;

public class NewUserBuyActivity extends BaseActivity implements OnClickListener {
    private TitleView mTitleView;
    private TextView mTotalAccount, mPayType;
    private RelativeLayout mSelectBankLayout;
    private TextView tvSelectbank;
    private EditText mCradNoTxt, mRealNameTxt, mIdNoTxt, mPhoneNumTxt;
    private Button btnPay;
    private OrderInfo orderInfo;
    private String payType;
    private String orderPrice;
    private int time = 1;
    private DialogWidget mDialogWidget;
    private PayPasswordView passwordView;
    private LinearLayout tipLayout;
    private RelativeLayout errorLayout;
    private TextView tvErrorContent;
    private String cardNo;
    private final int TAKEBANKCARDPHOTO_CODE = 1;
    private final int TAKEIDPHOTO_CODE = 2;
    private final int SELECT_BANK_CODE = 5;
    public final static String action1 = "idcard.scan";
    public final static String action2 = "bankcard.scan";
    public final static int SCAN_BANKCARD_SUCCESS = 3;
    public final static int SCAN_ID_SUCCESS = 4;
    private BankInfo bankInfo;
    private Handler handle = new Handler() {

        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0:
                    checkOrderStatus();
                    break;
                case SCAN_ID_SUCCESS:
                    PeopleBean bean = (PeopleBean) msg.obj;
                    if ("ok".equals(bean.getStatus())) {
                        PeopleBean.DataBean data = bean.getData();
                        PeopleBean.DataBean.ItemBean item = data.getItem();
                        if (!"[]".equals(item.getCardno())) {
                            mIdNoTxt.setText(item.getCardno());
                            mRealNameTxt.setText(item.getName());
                        } else {
                            UIHelper.showToast(NewUserBuyActivity.this, "获取身份信息失败!");
                        }
                    } else {
                        UIHelper.showToast(NewUserBuyActivity.this, "获取身份信息失败!");
                    }
                    break;
                case SCAN_BANKCARD_SUCCESS:
                    CardBean cardBean = (CardBean) msg.obj;
                    if (cardBean == null) {
                        return;
                    }
                    if ("OK".equals(cardBean.getStatus())) {
                        CardBean.DataBean data1 = cardBean.getData();
                        CardBean.DataBean.ItemBean item1 = data1.getItem();
                        if (item1.getCardno().length() < 15) {
                            UIHelper.showToast(NewUserBuyActivity.this, "获取银行卡信息失败!");
                        } else {
                            mCradNoTxt.setText(item1.getCardno());
                        }
                    } else {
                        UIHelper.showToast(NewUserBuyActivity.this, "获取银行卡信息失败!");
                    }
                    break;
                default:
                    break;
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_newuser_buy);
        initView();
    }

    private void initView() {
        Intent intent = this.getIntent();
        payType = intent.getStringExtra("payType");
        orderInfo = (OrderInfo) intent.getSerializableExtra("orderInfo");
        mTitleView = (TitleView) findViewById(R.id.title_view);
        mTitleView.getTitletextView().setVisibility(View.VISIBLE);
        mTitleView.getTitletextView().setText("添加银行卡");
        mTitleView.getBackView().setVisibility(View.VISIBLE);
        mTitleView.getBackView().setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mPayType = (TextView) findViewById(R.id.pay_type);
        mTotalAccount = (TextView) findViewById(R.id.total_amount);
        if (payType.equals("1")) {
            orderPrice = orderInfo.getCurrentOrderPrice();
            mTotalAccount.setText(orderInfo.getCurrentOrderPrice() + "元");
        } else if (payType.equals("2")) {
            mPayType.setText("钱包充值");
            orderPrice = orderInfo.getPayment();
            mTotalAccount.setText(orderInfo.getPayment() + "元");
        } else if (payType.equals("3")) {
            mPayType.setText("支付手续费");
            orderPrice = orderInfo.getFee();
            mTotalAccount.setText(orderInfo.getFee() + "元");
        } else if (payType.equals("4")) {
            mPayType.setText("手续费");
            orderPrice = orderInfo.getPayment();
            mTotalAccount.setText(orderInfo.getPayment() + "元");
        }
        mSelectBankLayout = (RelativeLayout) findViewById(R.id.select_bank_layout);
        tvSelectbank = (TextView) findViewById(R.id.tv_select_bank);
        mCradNoTxt = (EditText) findViewById(R.id.et_bank_no);
        mRealNameTxt = (EditText) findViewById(R.id.et_real_name);
        mRealNameTxt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                screenSpace(s, start, mRealNameTxt);
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mIdNoTxt = (EditText) findViewById(R.id.et_id_no);
        XEditUtils.set(mIdNoTxt, Strs.LETTER_NUMBER, null);
        mPhoneNumTxt = (EditText) findViewById(R.id.et_phone_num);
        tipLayout = (LinearLayout) findViewById(R.id.tip_layout);
        errorLayout = (RelativeLayout) findViewById(R.id.error_layout);
        tvErrorContent = (TextView) findViewById(R.id.txt_error_content);
        btnPay = (Button) findViewById(R.id.btn_pay);
        mSelectBankLayout.setOnClickListener(this);
        tipLayout.setOnClickListener(this);
        btnPay.setOnClickListener(this);
    }

    /**
     * 拍银行卡
     *
     * @param view
     */
    public void takePhoto(View view) {
        skipToACamera(TAKEBANKCARDPHOTO_CODE);
    }

    private void skipToACamera(int code) {
        Intent intent = new Intent(NewUserBuyActivity.this, ACameraActivity.class);
        intent.putExtra("type", code);
        startActivityForResult(intent, code);
    }

    /**
     * 拍身份证
     *
     * @param view
     */
    public void takeIDPhoto(View view) {
        skipToACamera(TAKEIDPHOTO_CODE);
    }

    protected void submitPayInfo(String vericode) {
        ActionUtil actionUtil = new ActionUtil(NewUserBuyActivity.this);
        actionUtil.submitPayInfo(cardNo, orderInfo.getOrderNo(), vericode, bankInfo.getGateName(), bankInfo.getSubGateName());
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (isFinishing()) {
                    return;
                }
                if (model == null) {
                    UIHelper.showToast(NewUserBuyActivity.this, getString(R.string.rank_fail));
                    return;
                }
                if (model.getErrorMsg() != null) {
                    if (model.getErrorCode().equals(Strs.EXTRUSION_SIGN_IN)) {
                        ActivityUtils.forceQuit(NewUserBuyActivity.this, getString(R.string.crowding_in_tips_txt));
                    } else {
                        UIHelper.showToast(NewUserBuyActivity.this, model.getErrorMsg());
                    }
                } else {
                    if ("true".equals(model.getStatus())) {
                        checkOrderStatus();
                    } else {
                        passwordView.clearUi();
                        UIHelper.showToast(NewUserBuyActivity.this, model.getInfo());
                    }
                }
            }
        });
    }

    protected void checkOrderStatus() {
        ActionUtil actionUtil = new ActionUtil(NewUserBuyActivity.this);
        actionUtil.searchOrderState(orderInfo.getOrderNo(), bankInfo.getGateName(), bankInfo.getSubGateName());
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (isFinishing()) {
                    return;
                }
                if (model == null) {
                    UIHelper.showToast(NewUserBuyActivity.this, NewUserBuyActivity.this.getString(R.string.rank_fail));
                    return;
                }
                if (model.getErrorMsg() != null) {
                    if (model.getErrorCode().equals(Strs.EXTRUSION_SIGN_IN)) {
                        ActivityUtils.forceQuit(NewUserBuyActivity.this, getString(R.string.crowding_in_tips_txt));
                    } else {
                        UIHelper.showToast(NewUserBuyActivity.this, model.getErrorMsg());
                    }
                } else {
                    if ("true".equals(model.getStatus())) {
                        passwordView.showSuccessUi();
                        new Thread(new Runnable() {
                            public void run() {
                                try {
                                    Thread.sleep(1000);
                                    if (payType.equals("1")) {
                                        String type = null;
                                        if ("HQ".equals(orderInfo.getOrderNo().substring(0, 2))) {
                                            type = "buyCurrentSuccess";
                                        } else {
                                            type = "buyRegularSuccess";
                                        }
                                        ActivityUtils.gotoTransRecord(NewUserBuyActivity.this, type);
                                    } else if (payType.equals("2")) {
                                        skipToWallet();
                                    } else if (payType.equals("3")) {
                                        ActivityUtils.gotoTransRecord(NewUserBuyActivity.this, "pickSuccess");
                                    } else if (payType.equals("4")) {
                                        ActivityUtils.gotoTransRecord(NewUserBuyActivity.this, "exchangeSuccess");
                                    }
                                    if (mDialogWidget != null) {
                                        mDialogWidget.dismiss();
                                    }
                                    mDialogWidget = null;

                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }).start();
                    } else {
                        time = time + 1;
                        if (time == 2) {
                            new Thread(new Runnable() {
                                public void run() {
                                    try {
                                        Thread.sleep(2000);
                                        handle.sendEmptyMessage(0);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }).start();
                        } else {
                            if (mDialogWidget != null) {
                                mDialogWidget.dismiss();
                            }
                            mDialogWidget = null;
                            if ("2".endsWith(payType)) {
                                new MyAlertDialog(NewUserBuyActivity.this).builder()
                                        .setMsg("暂时无法获取付款结果，请稍后转至资金明细页面查看。").setCancelable(false)
                                        .setPositiveButton("确定", true, new OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                ActivityUtils.skipToMain(NewUserBuyActivity.this, "orderFail");
                                            }
                                        }).show();
                            } else {
                                new MyAlertDialog(NewUserBuyActivity.this).builder()
                                        .setMsg("服务器繁忙，暂时无法获取付款结果，请稍后转至投资记录页面查看结果。").setCancelable(false)
                                        .setPositiveButton("确定", true, new OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                ActivityUtils.skipToMain(NewUserBuyActivity.this, "orderFail");
                                            }
                                        }).show();
                            }
                        }
                    }
                }
            }
        });
    }

    protected void getPayCode(String orderNo, final String realName, final String cardNo, final String idNo,
                              final String phoneNum, String orderAmount, final String payGate, final String subGate) {

        ActionUtil actionUtil = new ActionUtil(NewUserBuyActivity.this);
        actionUtil.getPayCode(orderNo, realName, cardNo, idNo, phoneNum, orderAmount, payGate, subGate);
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (isFinishing()){
                    return;
                }
                if (model == null) {
                    UIHelper.showToast(NewUserBuyActivity.this, getString(R.string.rank_fail));
                    return;
                }
                if (model.getErrorMsg() != null) {
                    if (model.getErrorCode().equals(Strs.EXTRUSION_SIGN_IN)) {
                        ActivityUtils.forceQuit(NewUserBuyActivity.this, getString(R.string.crowding_in_tips_txt));
                    } else {
                        UIHelper.showToast(NewUserBuyActivity.this, model.getErrorMsg());
                    }
                } else {
                    if ("0000".equals(model.getStatus())) {
                        updateUserInfo(realName, idNo);
                        CardInfo cardInfo = new CardInfo();
                        cardInfo.setCardNo(cardNo);
                        cardInfo.setRealName(realName);
                        cardInfo.setIdCard(idNo);
                        cardInfo.setPhone(phoneNum);
                        cardInfo.setPayGate(bankInfo.getGateName());
                        cardInfo.setSubGate(bankInfo.getSubGateName());
                        mDialogWidget = new DialogWidget(NewUserBuyActivity.this, getDecorViewDialog(cardInfo));
                        mDialogWidget.show();
                    } else {
                        UIHelper.showToast(NewUserBuyActivity.this, model.getInfo());
                    }
                }
            }
        });
    }

    private void updateUserInfo(String realName, String idNum) {
        DBOpenHelper helper = new DBOpenHelper(NewUserBuyActivity.this);
        String mobile = helper.getMobile();
        SQLiteDatabase db = helper.getReadableDatabase();
        String sql = "UPDATE HJB_USER  SET real_name='" + realName + "' WHERE mobile='" + mobile + "'";
        String sql1 = "UPDATE HJB_USER  SET id_card='" + idNum + "' WHERE mobile='" + mobile + "'";
        db.execSQL(sql);
        db.execSQL(sql1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case TAKEBANKCARDPHOTO_CODE:
                    final String result = data.getStringExtra("result");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            CardBean cardBean = ParserUtil.getNewModel(result, CardBean.class);
                            Message msg = new Message();
                            msg.what = SCAN_BANKCARD_SUCCESS;
                            msg.obj = cardBean;
                            handle.sendMessage(msg);
                        }
                    }).start();
                    break;
                case TAKEIDPHOTO_CODE:
                    final String idResult = data.getStringExtra("result");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            PeopleBean peopleBean = ParserUtil.getNewModel(idResult, PeopleBean.class);
                            Message msg = new Message();
                            msg.what = SCAN_ID_SUCCESS;
                            msg.obj = peopleBean;
                            handle.sendMessage(msg);
                        }
                    }).start();
                    break;
                case SELECT_BANK_CODE:
                    bankInfo = (BankInfo) data.getSerializableExtra("bankInfo");
                    tvSelectbank.setText(bankInfo.getBankName());
                    if (Double.parseDouble(orderPrice) > Double.parseDouble(bankInfo.getMoneyOnce())) {
                        errorLayout.setVisibility(View.VISIBLE);
                        tvErrorContent.setText(bankInfo.getBankDetail());
                        btnPay.setBackgroundColor(getResources().getColor(R.color.color_btn_enable));
                        btnPay.setEnabled(false);
                    } else {
                        errorLayout.setVisibility(View.GONE);
                        btnPay.setBackgroundColor(getResources().getColor(R.color.yellow_btn_bg));
                        btnPay.setEnabled(true);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    protected View getDecorViewDialog(CardInfo cardInfo) {

        passwordView = new PayPasswordView(3, 1, NewUserBuyActivity.this, orderInfo, orderPrice, cardInfo);

        passwordView.setOnPayListener(new OnPayListener() {

            @Override
            public void onSurePay(String password) {
                submitPayInfo(password);
            }

            @Override
            public void onCancelPay() {
                if (mDialogWidget != null) {
                    mDialogWidget.dismiss();
                }
                mDialogWidget = null;
            }
        });
        return passwordView.getView();
    }

    private void screenSpace(CharSequence s, int start, EditText view) {
        if (s.toString().contains(" ")) {
            String[] str = s.toString().split(" ");
            String str1 = "";
            for (int i = 0; i < str.length; i++) {
                str1 += str[i];
            }
            view.setText(str1);

            view.setSelection(start);
        }
    }

    private void skipToWallet() {
        Intent intent = new Intent();
        intent.setClass(NewUserBuyActivity.this, MyWalletActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tip_layout:
                new TipPopupView(NewUserBuyActivity.this, null, getString(R.string.bind_card_explain), R.style.MyDialog).show();
                break;
            case R.id.btn_pay:
                cardNo = mCradNoTxt.getText().toString().trim().replace(" ", "");
                String realName = mRealNameTxt.getText().toString();
                String idNo = mIdNoTxt.getText().toString();
                String phoneNum = mPhoneNumTxt.getText().toString();
                if (bankInfo == null) {
                    UIHelper.showToast(NewUserBuyActivity.this, "请选择银行!");
                    return;
                }
                if (TextUtils.isEmpty(cardNo)) {
                    UIHelper.showToast(NewUserBuyActivity.this, "请输入银行卡号!");
                    return;
                }

                if (TextUtils.isEmpty(realName)) {
                    UIHelper.showToast(NewUserBuyActivity.this, "请输入真实姓名!");
                    return;
                }
                if (TextUtils.isEmpty(idNo)) {
                    UIHelper.showToast(NewUserBuyActivity.this, "请输入身份证号!");
                    return;
                }
                if (TextUtils.isEmpty(phoneNum)) {
                    UIHelper.showToast(NewUserBuyActivity.this, "请输入手机号!");
                    return;
                }
                getPayCode(orderInfo.getOrderNo(), realName, cardNo, idNo, phoneNum, orderPrice, bankInfo.getGateName(), bankInfo.getSubGateName());
                break;
            case R.id.select_bank_layout:
                ActivityUtils.gotoSupportBank(NewUserBuyActivity.this, SELECT_BANK_CODE);
                break;
        }

    }
}
